package Cn.edu.zafu.bigdata.x.cxy;

import java.io.*;
import java.net.*;

public class UDPTimeClient {
    public static void main(String[] args) {
        try {
            // 创建一个DatagramSocket
            DatagramSocket clientSocket = new DatagramSocket();
            byte[] sendData = "What time is it?".getBytes();
            byte[] receiveData = new byte[1024];

            // 获取服务端的IP地址
            InetAddress serverAddress = InetAddress.getByName("127.0.0.1"); // 这里使用本地回环地址作为示例，实际使用时替换为服务器的IP地址

            // 发送请求到服务端
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9876);
            clientSocket.send(sendPacket);

            // 接收服务端返回的时间
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);

            // 打印时间
            String serverResponse = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("From server: " + serverResponse);

            // 关闭套接字
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}